package com.scratch.db.service;

import com.scratch.common.datasource.annotation.Isolate;
import com.scratch.common.redis.service.RedisService;
import com.scratch.common.service.db.DbService;
import com.scratch.common.service.db.DbTable;
import com.scratch.common.service.db.DbTypeEnum;
import com.scratch.common.service.db.DbUtils;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Set;

/**
 * Created by bpf on 2021/01/22.
 */

@Slf4j
@Component
public class SchedulingService implements SchedulingConfigurer {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private RedisService redisService;


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        DbService dbService = new DbService(dataSource, redisService);
        Reflections reflections = new Reflections("com.scratch.common.service.db.domain");
        Set<Class<?>> set = reflections.getTypesAnnotatedWith(DbTable.class);
        set.forEach(
                clazz -> {
                    DbTable dbTable = DbUtils.getDbTable(clazz);
                    switch (dbTable.type()) {
                        case INSERT:
                            taskRegistrar.addFixedDelayTask(() -> dbService.init(clazz, dbTable, DbTypeEnum.INSERT), dbTable.cron());
                            break;
                        case UPDATE:
                            taskRegistrar.addFixedDelayTask(() -> dbService.init(clazz, dbTable, dbTable.type()), dbTable.cron());
                            break;
                        case INSERT_AND_UPDATE:
                            taskRegistrar.addFixedDelayTask(() -> dbService.init(clazz, dbTable, DbTypeEnum.INSERT), dbTable.cron());
                            taskRegistrar.addFixedDelayTask(() -> dbService.init(clazz, dbTable, DbTypeEnum.UPDATE), dbTable.cron());
                            break;
                        default:
                            break;
                    }
                }
        );
    }

}